package wsp.dailymarket.auth;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Authentication Filter
 * @author Matt
 */
public class AuthFilter implements Filter {

	public void init(FilterConfig fc) throws ServletException {
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain fc) throws IOException, ServletException {
		AuthenticationBean authBean = (AuthenticationBean) ((HttpServletRequest) request).getSession().getAttribute("authenticationBean");
		if (authBean == null || authBean.getAuthentication() == null || !authBean.getAuthentication().isAuthorized()) {
			//String uri = (String) request.getAttribute("javax.servlet.forward.request_uri");
			((HttpServletResponse) response).sendRedirect("../login.do"); // Not logged in, so redirect to error page.
		} else {
			fc.doFilter(request, response); // Logged in, so just continue.
		}
	}

	public void destroy() {
	}
}
